<?php
/**
 * @filename QuestionCommand.php 
 * @encoding UTF-8 
 * @author KangShuAn
 * @datetime 2014-11-25 10:00:51
 * @version 1.0
 * @Description 问题附件压缩包处理
 */
set_time_limit(0);
ini_set('memory_limit', -1);
class QuestionCommand extends CConsoleCommand
{
    const SEPARATE_MARK = '-';//字段分隔符
    private $path = '';//解压目录
    private $unzip_file = '';//解压后的文件
    private $nqz_id = 0;//附件表索引
    
    private $file = '';//文件
    public function run($args){
	//得到未处理的问卷
        $zip = new NetworkQuestionZip();
        $criteria = new CDbCriteria();
        $criteria->addColumnCondition(array('is_dispose' => QuestionBase::QUESTION_ATTACHMENT));
	$list = $zip->findAll($criteria);
		
	if ($list) {
            foreach ($list as $key => $val) {
                $this->nqz_id = $val['nqz_id'];
                $this->file = dirname(Yii::app()->BasePath) .'/assets/zip/'.$val['question_id'].'_'.$val['nqz_num'].'.zip';
                if (file_exists($this->file)) {
                    //先把状态改了，改成正处理
                    NetworkQuestionZip::model()->updateByPk($this->nqz_id, array('update_time' => date('Y-m-d H:i:s'),'is_dispose' => QuestionBase::QUESTION_ATTACHMENT_UPLOADED));
                    $this->unzip();
                    $this->Up($val);
                } else {
                    NetworkQuestionZip::model()->updateByPk($this->nqz_id, array('update_time' => date('Y-m-d H:i:s'),'is_dispose' => QuestionBase::QUESTION_ATTACHMENT_EXECUTED,'remark' => '文件不存在'));
                }
            }
        }

    }

    /**
     * 上传附件
     * 扫描解压的文件，将附件一个个传到云平台
     * zip包名称为问卷编号，一个问卷一个zip包，里面是多个网点的
     * 101-A1.1-2.png
     * 网点编号-题目编号-附件序号
     */
    public function Up($zip_info){
        $bank_id = $zip_info['bank_id'];
        $project_id = $zip_info['project_id'];
        
        $arr = pathinfo($this->file);
	//问卷编号，压缩文件名称
        $identifier = explode('_',$arr['filename']);
        $question_id = $identifier[0];
        $base = new QuestionBase();
        $base_info = $base->findByPk($question_id);
	if (!$base_info) {
            //没有此问卷，要更新附件状态，下次不再处理
            NetworkQuestionZip::model()->updateByPk($this->nqz_id, array('update_time' => date('Y-m-d H:i:s'),'remark' => '没有此问卷','is_dispose' => QuestionBase::QUESTION_ATTACHMENT_EXECUTED));
            return false;
        }
        
        $fileobj = new File();
        //压缩文件目录
        $file = scandir($this->unzip_file);
        //错误信息
        $error = array();
	if ($file !== false) {
            foreach ($file as $val) {
                if ($val =='.' || $val=='..') continue; 
                $absolue_file = $this->unzip_file.DIRECTORY_SEPARATOR.$val;
                if (!is_dir($absolue_file)) {
                    $pathinfo = pathinfo($val);
                    $filename = $pathinfo['filename'];
                    //每个附件的名称
                    $attachment = explode(self::SEPARATE_MARK, $filename);
                    if (count($attachment) < 2) {
                        $error[] = $filename.'名称错误';
                        continue;
                    }
                    //网点编号
                    $network_num = $attachment[0];
                    //根据网点编号查找id
                    $network = new NetWork();
                    $network_info = $network->getByNetworkNum($network_num, $bank_id);
                    if (!$network_info) {
                        $error[] = $network_num.'网点编号不存在';
                        continue;
                    }
                    $network_id = (int)$network_info['network_id'];
                    echo '网点ID'.$network_id."\r\n";
                    //题目编号
                    $question_num = $attachment[1];
                    echo '题目编号'.$question_num."\r\n";
                    //根据题目编号查找题目id
                    $subject = new QuestionSubject();
                    $subject_info = $subject->find("question_num='{$question_num}' and question_id={$question_id}");
                    if (!$subject_info) {
                        $error[] = $question_num.'题目编号不存在';
                        continue;
                    }
                    $subject_id = (int)$subject_info['subject_id'];
                    echo "题目ID".$subject_id."\r\n";
                    //网点问卷ID
                    $networkquestion = new NetworkQuestion();
                    $networkquestion_info = $networkquestion->getByNetworkQuestion($network_id, $question_id);
                    if (!$networkquestion_info) {
                        $error[]  = '查不到网点问卷'.$network_id;
                        continue;
                    }
                    $nq_id = $networkquestion_info['nq_id'];
                    echo '网点问卷ID'.$nq_id."\r\n";
                    $file_dir = $this->unzip_file.DIRECTORY_SEPARATOR.$val;
                    echo $file_dir . " 开始上传~~\r\n";
                    //上传,下载时用中文名

                    $download_name = $network_info['network_name'].'-'.$subject_info['question_num'].'-'.time().'.'.$pathinfo['extension'];
                    //echo $download_name."\r\n";
                    $url = $fileobj->uploadByFile($val, $file_dir,'zhengda-benchmark',$download_name);
                    echo "返回url：".$url."\r\n";
					
                    //上传成功
                    if ($url) {
                        //如果有同名的替换
                        if ($question_attach = NetworkQuestionAttach::model()->find("nq_id={$nq_id} and subject_id={$subject_id} and filename='{$val}'")) {

                        } else {
                            $question_attach = new NetworkQuestionAttach();
                        }
                        //保存附件 
                        $question_attach->nq_id = $nq_id;
                        $question_attach->subject_id = $subject_id;
                        $question_attach->url = $url;
                        $question_attach->filename = $val;
                        $question_attach->create_time = time();
                        $question_attach->update_time = time();
                        $attachSave = $question_attach->save();
                        if ($attachSave) {
                            echo "network_question id ". $nq_id ."，附件表写入成功！\r\n";
                        }
                    }
                } else {
                    $error[] = '存在二级目录';
                }
            }
            if (empty($error)) {
                $error[] = '解压上传成功';
            }
            NetworkQuestionZip::model()->updateByPk($this->nqz_id, array('update_time' => date('Y-m-d H:i:s'),'is_dispose' => QuestionBase::QUESTION_ATTACHMENT_EXECUTED,'remark' => join(',', $error)));
            echo "question_base 附件状态更新成功\r\n";
        }
        echo "zip done\r\n";
        exit;
    }
    /**
     * 
     * @param type $file
     * 解压同级目录
     */
    private function unzip(){
        $zip = new ZipArchive();
        $res = $zip->open($this->file);
        $this->unzip_file = substr($this->file, 0, -4);
	if ($res === true) {
            $zip->extractTo($this->unzip_file);
            $zip->close();
        }
    } 
	
 
}